package Map_and_Set.Leetcode;

import java.util.HashMap;
import java.util.Map;

/**
 * 复制带随机指针的链表
 */
public class Num138 {
    public Node copyRandomList(Node head) {
      //遍历原链表，使用Map集合维护原链表节点和新链表节点的映射关系
        Map<Node,Node> map=new HashMap<>();
        for (Node x=head;x!=null;x=x.next){
            Node node=new Node(x.val);
            map.put(x,node);
        }
        //再次遍历原链表，通过映射关系维护新链表的next和random
        for (Node x=head;x!=null;x=x.next){
            //原1.next=原3
            //新1.next=新3
            map.get(x).next=map.get(x.next);
            //原1.random=原5
            //新1.random=新5
            map.get(x).random=map.get(x.random);
        }
        return map.get(head);
    }
}

class Node {
    int val;
    Node next;
    Node random;

    public Node(int val) {
        this.val = val;
        this.next = null;
        this.random = null;
    }
}
